package com.example.demo.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.example.demo.dto.AuthUserDto;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
@Slf4j
public class CaptchaController {
    @Autowired
    private StringRedisTemplate redisTemplate; // 注入Redis操作类

    @GetMapping("/code")
    public Map<String, Object> getCaptcha(HttpServletRequest request, HttpServletResponse response)  throws IOException {
        RandomGenerator randomGenerator = new RandomGenerator("0123456789",4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200,100);
        lineCaptcha.setGenerator(randomGenerator);
        lineCaptcha.createCode();
        String code = lineCaptcha.getCode();
        String answer = String.valueOf(new MathGenerator().generate()); // 计算 "2+3" 的结果，得到 "5"
        HttpSession session = request.getSession();
        session.setAttribute("CAPTCHA_ANSWER", answer);
        String imageData = "data:image/png;base64," + lineCaptcha.getImageBase64();
        String uniqueId = UUID.randomUUID().toString();
        String captchaUuid = "captcha_code:" + uniqueId;
        // 4. 存储到Redis (有效期5分钟)
        redisTemplate.opsForValue().set(uniqueId, code, 5, TimeUnit.MINUTES);
        //返回数据
   // 4、设置响应头禁止缓存
        response.setHeader("Cache-Control", "no-store, no-cache");
        Map<String, Object> responseBody  = new HashMap<>();
        responseBody.put("uuid", captchaUuid);
        responseBody.put("img", imageData);
        return responseBody;
    }

    @PostMapping("/login")
    public ResponseEntity login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception {
           String code = redisTemplate.opsForValue().get(authUser.getUuid());
           if(StrUtil.isBlank(code)) {
               throw new BadRequestException("验证码不存在或已过期");
           }
           String codeSum = authUser.getCode();
           if(StrUtil.isBlank(codeSum) || !codeSum.equalsIgnoreCase(code)) {
               throw new BadRequestException("验证码错误");
           }
           return ResponseEntity.ok(authUser);
    }
}
